#define  _CRT_SECURE_NO_WARNINGS 1

#include "Queue.h"

void QueueInit(pQueue pq)
{
	assert(pq);

	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}


pQNode BuyQueueNode(QDataType x)
{
	pQNode newnode = (pQNode)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	newnode->val = x;
	newnode->next = NULL;

	return newnode;
}


void QueuePush(pQueue pq, QDataType x)
{
	assert(pq);
	
	pq->size++;
	pQNode newnode = BuyQueueNode(x);
	if (pq->phead == NULL)
	{
		pq->phead = pq->ptail = newnode;
	}
	else
	{
		pq->ptail->next = newnode;
		pq->ptail = newnode;
	}
}


void QueuePop(pQueue pq)
{
	assert(pq && pq->phead);
	pq->size--;

	if (pq->phead == pq->ptail)
	{
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
	}
	else
	{
		pQNode next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}
}


void QueueDestory(pQueue pq)
{
	assert(pq);

	pQNode cur = pq->phead;
	while (cur)
	{
		pQNode next = cur->next;
		free(cur);
		cur = next;
	}
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}


bool QueueEmpty(pQueue pq)
{
	assert(pq);

	return pq->phead == NULL;
}


int QueueSize(pQueue pq)
{
	assert(pq);

	return pq->size;
}


QDataType QueueFront(pQueue pq)
{
	assert(pq);

	return pq->phead->val;
}


QDataType QueueBack(pQueue pq)
{
	assert(pq);

	return pq->ptail->val;
}


MyStack* myStackCreate() {
	MyStack* obj = (MyStack*)malloc(sizeof(MyStack));
	QueueInit(&obj->q1);
	QueueInit(&obj->q2);

	return obj;
}

void myStackPush(MyStack* obj, int x) {
	if (!QueueEmpty(&obj->q1))
	{
		QueuePush(&obj->q1, x);
	}
	else {
		QueuePush(&obj->q2, x);
	}
}

int myStackPop(MyStack* obj) {
	pQueue empty = &obj->q1, NonEmpty = &obj->q2;
	if (!QueueEmpty(empty))
	{
		empty = &obj->q2;
		NonEmpty = &obj->q1;
	}
	while (QueueSize(NonEmpty) > 1)
	{
		QueuePush(empty, QueueFront(NonEmpty));
		QueuePop(NonEmpty);
	}
	int ret = QueueFront(NonEmpty);
	QueuePop(NonEmpty);

	return ret;
}

int myStackTop(MyStack* obj) {
	if (!QueueEmpty(&obj->q1))
		return QueueBack(&obj->q1);
	else {
		return obj->q2.ptail->val;
	}
}

bool myStackEmpty(MyStack* obj) {
	return QueueEmpty(&obj->q1) && QueueEmpty(&obj->q2);
}

void myStackFree(MyStack* obj) {
	QueueDestory(&obj->q1);
	QueueDestory(&obj->q2);
	free(obj);
}